package com.example.mymvvmdemo.base;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.WindowManager;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewbinding.ViewBinding;

import com.example.mymvvmdemo.ActivityCollector;
import com.example.mymvvmdemo.MyApplication;
import com.example.mymvvmdemo.utils.LogUtils;
import com.example.mymvvmdemo.utils.MyActivityUtils;
import com.example.mymvvmdemo.utils.NotchScreenUtil;
import com.example.mymvvmdemo.utils.ToastUtils;
import com.google.gson.Gson;
import com.gyf.immersionbar.ImmersionBar;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

/**
 * 带加载框的baseActivity
 */
public abstract class BaseLoadActivity<VB extends ViewBinding> extends AppCompatActivity {

    public VB binding;
    public Gson gson;
    //是否有状态栏
    private boolean hasNavigationBar;
    //状态栏高度
    public int statusBarHeight;

    public static final int PERMISSION_REQ_ID_WRITE_EXTERNAL_STORAGE = 0X0001;
    private static final int CACHE_SIZE = 200;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        gson = new Gson();
        initVB();
        initView(savedInstanceState);
        createDialog();
        initData();
        initDialog();
        initListener();
        ImmersionBar.with(this).statusBarDarkFont(true)
                .transparentNavigationBar()
                .fullScreen(false)
                .init();
        ActivityCollector.addActivity(this);
        hasNavigationBar = ImmersionBar.hasNavigationBar(this);
        if (hasNavigationBar) {
            statusBarHeight = NotchScreenUtil.getNotchSize(this)[1];
        }
        initStatusBar();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        destroyDialog();
        ActivityCollector.removeActivity(this);
    }

    private void initVB() {
        Type superclass = getClass().getGenericSuperclass();
        Class<?> aClass = (Class<?>) ((ParameterizedType) superclass).getActualTypeArguments()[0];
        try {
            Method method = aClass.getDeclaredMethod("inflate", LayoutInflater.class);
            binding = (VB) method.invoke(null, getLayoutInflater());
            setContentView(binding.getRoot());
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            LogUtils.e(e.getMessage());
        }

    }

    public void initView(Bundle savedInstanceState) {
    }

    protected abstract void showDialog();

    protected abstract void dismissDialog();

    protected abstract void initData();

    protected abstract void initListener();

    //创建dialog
    public void initDialog() {

    }

    //创建dialog
    public void createDialog() {

    }

    //销毁dialog
    private void destroyDialog() {

    }

    //适配状态栏
    public void initStatusBar() {

    }

    public void toast(String message, int type) {
        ToastUtils.getToastUtils().toast(message, type);
    }

    public void toast(int resId, int type) {
        ToastUtils.getToastUtils().toast(this, resId, type);
    }

    public void toast(String resId, boolean isRun, int type) {
        if (isRun) {
            if (!MyActivityUtils.isForeground(this)) {
                return;
            }
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ToastUtils.getToastUtils().toast(resId, type);
                }
            });
        } else {
            ToastUtils.getToastUtils().toast(resId, type);
        }
    }

    public void toast(int resId, boolean isRun, int type) {
        if (isRun) {
            if (!MyActivityUtils.isForeground(this)) {
                return;
            }
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ToastUtils.getToastUtils().toast(MyApplication.getContext(), resId, type);
                }
            });
        } else {
            ToastUtils.getToastUtils().toast(this, resId, type);
        }
    }

//    @Override
//    protected void attachBaseContext(Context newBase) {
//        Context context = MultiLanguageUtil.attachBaseContext(newBase);
//        final Configuration configuration = context.getResources().getConfiguration();
//        // 此处的ContextThemeWrapper是androidx.appcompat.view包下的
//        // 你也可以使用android.view.ContextThemeWrapper，但是使用该对象最低只兼容到API 17
//        // 所以使用 androidx.appcompat.view.ContextThemeWrapper省心
//        final ContextThemeWrapper wrappedContext = new ContextThemeWrapper(context,
//                androidx.appcompat.R.style.Theme_AppCompat_Empty) {
//            @Override
//            public void applyOverrideConfiguration(Configuration overrideConfiguration) {
//                if (overrideConfiguration != null) {
//                    overrideConfiguration.setTo(configuration);
//                }
//                super.applyOverrideConfiguration(overrideConfiguration);
//            }
//        };
//        super.attachBaseContext(wrappedContext);
//
//    }

    /**
     * 判断是否是竖屏状态
     *
     * @return
     */
    public boolean isLongitudinal() {
        //TODO 这里遇到一个问题，高版本三星手机获取的横竖屏状态有误，为解决这个问题，根据屏幕宽高判断横竖屏
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        int widthPixels = dm.widthPixels;
        int heightPixels = dm.heightPixels;
        if (heightPixels > widthPixels)
            return true;
        else if (heightPixels < widthPixels)
            return false;

        return getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;
    }

    /**
     * 得到屏幕高度
     */
    public int getScreenHeight() {
        WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics displayMetrics = new DisplayMetrics();
        windowManager.getDefaultDisplay().getMetrics(displayMetrics);
        return displayMetrics.heightPixels;
    }

    /**
     * 得到屏幕宽度
     */
    public int getScreenWidth() {
        WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics displayMetrics = new DisplayMetrics();
        windowManager.getDefaultDisplay().getMetrics(displayMetrics);
        return displayMetrics.widthPixels;
    }

    /**
     * 便携式跳转activity
     *
     * @param activityClass 目标activity
     */
    public void startActivity(Class<?> activityClass) {
        Intent intent = new Intent(MyApplication.getInstance(), activityClass);
        startActivity(intent);
    }

    /**
     * 获取SSID
     *
     * @param
     * @return WIFI 的SSID
     */
    public String getWIFISSID() {
        String ssid = "";
        //android 8.1
        if (Build.VERSION.SDK_INT == Build.VERSION_CODES.O_MR1) {
            ConnectivityManager connManager = (ConnectivityManager) getApplicationContext().getSystemService(CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = connManager.getActiveNetworkInfo();
            LogUtils.d("1:" + networkInfo.toString());
            if (networkInfo != null) {
                if (networkInfo.isConnected()) {
                    if (networkInfo.getExtraInfo() != null) {
                        return networkInfo.getExtraInfo().replace("\"", "");
                    }
                }
            } else {
                return ssid;
            }
        } else {
            WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
            WifiInfo info = wifiManager.getConnectionInfo();
            LogUtils.d("2:" + info.toString());
            String ssid1 = info.getSSID();
            LogUtils.d("ssid1:" + ssid1);
            if (ssid1.contains("unknown ssid")) {
                return ssid;
            }
            if (ssid1.length() > 1) {
                String substring = ssid1.substring(1, ssid1.length() - 1);
                LogUtils.d("substring:" + substring);
                return substring;
            }
            return info.getSSID();
        }
        return ssid;
    }


}
